﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
using System.Configuration;
using System.Text.RegularExpressions;
using System.IO;
using System.Configuration;
using WiSContactData.util;

namespace WiSContactData
{
    public partial class WiSContactData : ServiceBase
    {
        [DllImport("kernel32.dll")]
        static extern IntPtr CreateEvent(IntPtr lpEventAttributes, bool bManualReset, bool bInitialState, string lpName);

        [DllImport("Kernel32.dll", SetLastError = true)]
        static extern IntPtr OpenEvent(uint dwDesiredAccess, bool bInheritHandle, string lpName);

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);

        const uint STANDARD_RIGHTS_REQUIRED = 0x000F0000;
        const uint SYNCHRONIZE = 0x00100000;
        const uint EVENT_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3);
        const UInt32 INFINITE = 0xFFFFFFFF;

        IntPtr hdlCreate, hdlOpen;

        bool isThreadRunning = true;
        public WiSContactData()
        {
            InitializeComponent();
            loadSetting();
        }
        private void loadSetting()
        {
            if (!System.Diagnostics.EventLog.SourceExists("WiSContactData_Source"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                   "WiSContactData_Source", "WiSContactData_Log");
            }
            evlWiSContactData.Source = "WiSContactData_Source";
            evlWiSContactData.Log = "WiSContactData_Log";
        }
        private void logToSystem(string msg, EventLogEntryType eventLogEntryType)
        {

            evlWiSContactData.WriteEntry(msg, eventLogEntryType);
        }
        protected override void OnStart(string[] args)
        {
            try
            {
                logToSystem("On Start " + DateTime.Now.ToString(), EventLogEntryType.Information);
                hdlCreate = CreateEvent(IntPtr.Zero, false, false, "Global\\WiSContactData");

                if (hdlCreate != IntPtr.Zero)
                {
                    logToSystem("Handle created successfully. Value: " + hdlCreate.ToString(), EventLogEntryType.Information);
                    hdlOpen = OpenEvent(EVENT_ALL_ACCESS, false, "Global\\WiSContactData");
                    if (hdlOpen != IntPtr.Zero)
                    {
                        logToSystem("Handle openned successfully. Value: " + hdlOpen.ToString(), EventLogEntryType.Information);

                        Thread thread = new Thread(processWiSDequeue);
                        thread.Start();

                    }
                }
                else
                {
                    logToSystem("Failed created. Value: " + hdlCreate.ToString(), EventLogEntryType.Error);
                }

            }
            catch (Exception ex)
            {
            }
        }
        public WeSMsg.Email bath (WeSContactData.ContactData data)
        {
            WeSMsg.Email email = new WeSMsg.Email();
            DataTable dt  = null;
            DataTable dt2 = null;
            dt = DB.getData("select * from MSGTYPE where Id = " + data.msgTypeId + ";");
            string msgName = dt.Rows[0]["Name"].ToString();
            int roleID = Convert.ToInt32(dt.Rows[0]["RoleId"]);
            dt = DB.getData("select UserID from ROLEUSER where RoleID = " + roleID +";");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int userID = Convert.ToInt32(dt.Rows[i]["UserID"]);
                dt2 = DB.getData("select Email from SYSUSER where Id = "+userID+";");
                email.emailTo = email.emailTo +","+ dt2.Rows[0]["Email"].ToString();
            }
            email.subject="MsgName: "+msgName + " - ContactDataId: " + data.id.ToString() + "Status: "+ data.status;
            email.body = "<b>Request Info:</b><br/>Name=" +data.name+"<br/>Mobile="+data.mobile+"<br>/Email= "+data.email+"<br/><b>MsgContent:</b><p>"
                            +data.msgContent+"</p><b>Remark:</b><p>"+data.remark+"</p>";
            email.isHTMLEncoded = true;
            email.emailFrom = "";
            email.fileName = "";
            return email;
            
        }
        public void processWiSDequeue()
        {
            try
            {
                using (WeSContactData.WeSContactDataClient client = new WeSContactData.WeSContactDataClient())
                {
                    logToSystem("WiSContactData Thread start dequeue " + DateTime.Now.ToString(), EventLogEntryType.Information);
                    while (isThreadRunning)
                    {
                        WeSContactData.WeSContactDataDequeueResult dequeue = new WeSContactData.WeSContactDataDequeueResult();

                        //WeSMsg.Email mail = new WeSMsg.Email();
                        
                        dequeue = client.Dequeue();
                        while (dequeue.contactDataResult.statusCode==0)
                        {

                            using (WeSMsg.WeSMsgClient client2 = new WeSMsg.WeSMsgClient())
                            {
                                logToSystem("WiSContactData start enqueueEmail " + DateTime.Now.ToString(), EventLogEntryType.Information);
                                WeSMsg.WeSMsgEnqueueResult enqueueEmail = new WeSMsg.WeSMsgEnqueueResult();
                                enqueueEmail=client2.enqueue(bath(dequeue.contactData));
                                
                            }
                            dequeue = client.Dequeue();
                          

                        }

                        logToSystem("WiSContactData Thread waiting for enqueue " + DateTime.Now.ToString(), EventLogEntryType.Information);
                        WaitForSingleObject(hdlOpen, INFINITE);
                        logToSystem("WiSContactData Thread resume working on " + DateTime.Now.ToString(), EventLogEntryType.Information);

                    }

                }

            }
            catch (Exception ex)
            {

            }

        }


        protected override void OnStop()
        {
            try
            {
                logToSystem("On stop " + DateTime.Now.ToString(), EventLogEntryType.Information);
                isThreadRunning = false;
            }
            catch (Exception ex)
            {
            }
        }
    }
}
